/*****************************************************************************
 * Copyright (c) 2022, Nations Technologies Inc.
 *
 * All rights reserved.
 * ****************************************************************************
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *
 * - Redistributions of source code must retain the above copyright notice,
 * this list of conditions and the disclaimer below.
 *
 * Nations' name may not be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * DISCLAIMER: THIS SOFTWARE IS PROVIDED BY NATIONS "AS IS" AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT ARE
 * DISCLAIMED. IN NO EVENT SHALL NATIONS BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA,
 * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
 * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
 * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 * ****************************************************************************/

/**
 * @file n32l40x_it.c
 * @author Nations
 * @version V1.2.2
 *
 * @copyright Copyright (c) 2022, Nations Technologies Inc. All rights reserved.
 */
#include "n32l40x_it.h"
#include "n32l40x.h"
#include "main.h"
#include "my_uart.h"
/** @addtogroup N32L40X_StdPeriph_Template
 * @{
 */

extern __IO uint32_t CurrDataCounterEnd;

extern uint8_t uartz_tx_buff[];
extern uint8_t uartz_rx_buff[];

extern uint8_t uarty_tx_buff[];
extern uint8_t uarty_rx_buff[];

extern __IO uint8_t TxCounter1;
extern __IO uint8_t TxCounter2;
extern __IO uint8_t RxCounter1;
extern __IO uint8_t RxCounter2;
extern uint8_t NbrOfDataToTransfer1;
extern uint8_t NbrOfDataToTransfer2;
extern uint8_t NbrOfDataToRead1;
extern uint8_t NbrOfDataToRead2;


extern __IO uint16_t CCR1_Val;
extern __IO uint16_t CCR2_Val;
uint16_t capture = 0;

/******************************************************************************/
/*            Cortex-M4 Processor Exceptions Handlers                         */
/******************************************************************************/

/**
 * @brief  This function handles NMI exception.
 */
void NMI_Handler(void)
{
}

/**
 * @brief  This function handles Hard Fault exception.
 */
void HardFault_Handler(void)
{
    /* Go to infinite loop when Hard Fault exception occurs */
    while (1)
    {
    }
}

/**
 * @brief  This function handles Memory Manage exception.
 */
void MemManage_Handler(void)
{
    /* Go to infinite loop when Memory Manage exception occurs */
    while (1)
    {
    }
}

/**
 * @brief  This function handles Bus Fault exception.
 */
void BusFault_Handler(void)
{
    /* Go to infinite loop when Bus Fault exception occurs */
    while (1)
    {
    }
}

/**
 * @brief  This function handles Usage Fault exception.
 */
void UsageFault_Handler(void)
{
    /* Go to infinite loop when Usage Fault exception occurs */
    while (1)
    {
    }
}

/**
 * @brief  This function handles SVCall exception.
 */
void SVC_Handler(void)
{
}

/**
 * @brief  This function handles Debug Monitor exception.
 */
void DebugMon_Handler(void)
{
}

/**
 * @brief  This function handles SysTick Handler.
 */
void SysTick_Handler(void)
{
}

/**
 * @brief  This function handles DMA interrupt request defined in main.h .
 */
void DMA_IRQ_HANDLER(void)
{
}

/******************************************************************************/
/*                 n32l40x Peripherals Interrupt Handlers                     */
/*  Add here the Interrupt Handler for the used peripheral(s) (PPP), for the  */
/*  available peripheral interrupt handler's name please refer to the startup */
/*  file (startup_n32l40x.s).                                                 */
/******************************************************************************/

/******************************************************************************/
/*                 N32L40X Peripherals Interrupt Handlers                     */
/*  Add here the Interrupt Handler for the used peripheral(s) (PPP), for the  */
/*  available peripheral interrupt handler's name please refer to the startup */
/*  file (startup_n32l40x.s).                                                 */
/******************************************************************************/

#include "sys_param.h"


/*****************************************************
 *  EMS的占空比，在这里调节：
 *   配置为TIM_SetCmp1(TIM2, 0); TIM_SetCmp2(TIM2, CCR2_Val*1/4); 时，周期 375us，移相高电平持续时间 32us
 *   配置为TIM_SetCmp1(TIM2, 0); TIM_SetCmp2(TIM2, CCR2_Val*2/4); 时，周期 375us，移相高电平持续时间 64us
 * 
*******************************************************/
void TIM2_IRQHandler(void)
{
        /* TIM3_CH1 toggling with frequency = 183.1 Hz */
    if (TIM_GetIntStatus(TIM2, TIM_INT_CC1) != RESET)
    {
        TIM_ClrIntPendingBit(TIM2, TIM_INT_CC1);
        capture = TIM_GetCap1(TIM2);
        TIM_SetCmp1(TIM2, 0);
    }

    /* TIM3_CH2 toggling with frequency = 366.2 Hz */
    if (TIM_GetIntStatus(TIM2, TIM_INT_CC2) != RESET)
    {
        TIM_ClrIntPendingBit(TIM2, TIM_INT_CC2);
        capture = TIM_GetCap2(TIM2);
        // TIM_SetCmp2(TIM2, CCR2_Val*1/7);    // ems 20khz,对应的参数 CCR2_Val*1/7
        TIM_SetCmp2(TIM2, CCR2_Val*1/12);  
    }
}

//extern SYS_PARAM_t sys_data;
/**
 * @brief  This function handles TIM2 global interrupt request.
 */
static int task_250us_cnt;
void TIM3_IRQHandler(void)
{
    if (TIM_GetIntStatus(TIM3, TIM_INT_UPDATE) != RESET)
    {
        TIM_ClrIntPendingBit(TIM3, TIM_INT_UPDATE);

        sys_data.task_125us_flag = 1;
        task_250us_cnt ++;
        if(0 == task_250us_cnt%8){
            task_250us_cnt = 0;
            sys_data.task_1ms_flag = 1;
        }
        /* Pin PC.06 toggling */
       // GPIO_WriteBit(GPIOC, GPIO_PIN_6, (Bit_OperateType)(1 - GPIO_ReadOutputDataBit(GPIOC, GPIO_PIN_6)));
    }
}


void TIM6_IRQHandler(void)
{
    if (TIM_GetIntStatus(TIM6, TIM_INT_UPDATE) != RESET)
    {
        TIM_ClrIntPendingBit(TIM6, TIM_INT_UPDATE);
        sys_data.task_1s_flag = 1;
    }
}

/**
 * @brief  This function handles USARTy global interrupt request.
 */
void USARTy_IRQHandler(void)
{
#ifdef USARTy
    if (USART_GetIntStatus(USARTy, USART_INT_RXDNE) != RESET)
    {
        /* Read one byte from the receive data register */
        uarty_rx_buff[RxCounter1++] = USART_ReceiveData(USARTy);

        if (RxCounter1 == NbrOfDataToRead1)
        {
            /* Disable the USARTy Receive interrupt */
            USART_ConfigInt(USARTy, USART_INT_RXDNE, DISABLE);
        }
    }

    if (USART_GetIntStatus(USARTy, USART_INT_TXDE) != RESET)
    {
        /* Write one byte to the transmit data register */
        USART_SendData(USARTy, uarty_rx_buff[TxCounter1++]);

        if (TxCounter1 == NbrOfDataToTransfer1)
        {
            /* Disable the USARTy Transmit interrupt */
            USART_ConfigInt(USARTy, USART_INT_TXDE, DISABLE);
        }
    }
    if(USART_GetIntStatus(USARTy, USART_INT_OREF) != RESET)
    {
        /*Read the STS register first,and the read the DAT 
        register to clear the overflow interrupt*/
        (void)USARTy->STS;
        (void)USARTy->DAT;
    }
#endif    
}


/*串口中断服务函数,串口空闲中断*/
void USARTz_IRQHandler(void)
{
    uint16_t usTemp = 0;      //当前数据个数
	if(USART_GetIntStatus(USARTz, USART_INT_IDLEF)!=RESET)
	{		
		USART_ReceiveData(USARTz);				//为了清除中断
		//先关闭DMA接收
		DMA_EnableChannel(USARTz_Rx_DMA_Channel, DISABLE);
		//清一下DMA中断标志位，因为没有触发也可以不清
		DMA_ClrIntPendingBit(USARTz_Rx_DMA_INT, DMA);
		//实际接收数据个数
		usTemp = USARTz_MAX_BUFF_SIZE - DMA_GetCurrDataCounter(USARTz_Rx_DMA_Channel);		
		// //处理数据，发送数据
		// uartx_send_data(usTemp);
        uart_data.recv_flag = 1;
        uart_data.recv_num = usTemp;
		//最后设置接收个数，打开接收
		DMA_SetCurrDataCounter(USARTz_Rx_DMA_Channel, USARTz_MAX_BUFF_SIZE); 
		DMA_EnableChannel(USARTz_Rx_DMA_Channel, ENABLE);
	}	 
}

/*DMA发送完成中断，发送完成之后关闭发送通道，等待下次发送再打开*/
void USARTz_Tx_DMA_IRQHandler(void)
{
    if(DMA_GetIntStatus(USARTz_Tx_DMA_INT, DMA) != RESET)
    {            
        DMA_EnableChannel(USARTz_Tx_DMA_Channel, DISABLE);
        DMA_ClrIntPendingBit(USARTz_Tx_DMA_INT, DMA);         
    }     
}

/*DMA接收完成中断，正常情况可以不用*/
void USARTz_Rx_DMA_IRQHandler(void)
{
    if(DMA_GetIntStatus(USARTz_Rx_DMA_INT, DMA) != RESET)
    {            
        DMA_EnableChannel(USARTz_Rx_DMA_Channel, DISABLE);//关闭DMA通道	
        DMA_ClrIntPendingBit(USARTz_Rx_DMA_INT, DMA);     //清楚标志位
        DMA_SetCurrDataCounter(USARTz_Rx_DMA_Channel, USARTz_MAX_BUFF_SIZE);//设置传输长度  	
        DMA_EnableChannel(USARTz_Rx_DMA_Channel, ENABLE); //最后打开DMA通道	   
    }     
}



/**
 * @brief  This function handles the PVD Output interrupt request defined in main.h .
 */

int power_key_cnt = 0;

void EXTI15_10_IRQHandler(void)
{
    if (EXTI_GetITStatus(EXTI_LINE14) != RESET)
    {
        /* Clear the Key Button EXTI line pending bit */
        EXTI_ClrITPendBit(EXTI_LINE14);
        if((sys_data.sta == SLEEP_STA)&&(sys_data.beep_finish_flag == 0)){
            power_key_cnt ++;
//					if(power_key_cnt > 2){
//							NVIC_SystemReset();
//					}
            NVIC_SystemReset();
        }
        else{
            power_key_cnt = 0; 
        }
			
    }
}


/**
 * @}
 */
